<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/22
 * Time: 11:19
 */
namespace App;
require '../vendor/qiniu/php-sdk/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
class GetTokenQn
{
    private $accessKey = 'j7ReX_n5WEo4bzndCQiiVThOdJYL1Z_iG6LqYwuy';
    private $secretKey = 'Uhr4rezlsrnSkKJbxMMYiklezg1aj7nLkpC5pW0M';
    private $bucKet = 'business';

    /*
    获取上传凭证token
    */
    public function getVideoToken()
    {
        $auth = new Auth( $this->accessKey, $this->secretKey );
        $token = $auth->uploadToken( $this->bucKet );
        return ['uptoken'=>$token,'domain'=>config('constants.QINIU_URL')];
    }
    public function getToken()
    {
        $auth = new Auth($this->accessKey, $this->secretKey);
        $token = $auth->uploadToken($this->bucKet);
        return $token;
    }
    /*
    获取下载凭证url
    */


    public function getDownloadUrl( $key )
    {
        return config('constants.QINIU_URL').$key;
    }
    /*
    验证上传文件格式
    */

    public function validateFormat( $file )
    {
        $allowedExts = array("jpeg","jpg","png","avi","mov","rmvb","rm","flv","mp4","3gp");
        $temp = explode(".",$file['name']);
        $extension = end($temp);
        if ((($file["type"] == "image/gif")
                || ($file["type"] == "image/jpeg")
                || ($file["type"] == "image/jpg")
                || ($file["type"] == "image/pjpeg")
                || ($file["type"] == "image/x-png")
                || ($file["type"] == "image/png")
                || ($file["type"] == "video/avi")
                || ($file["type"] == "video/quicktime")
                || ($file["type"] == "video/rmvb")
                || ($file["type"] == "video/rm")
                || ($file["type"] == "video/flv")
                || ($file["type"] == "video/mp4")
                || ($file["type"] == "video/3gp"))
            && in_array($extension, $allowedExts))
        {
            if ($file["error"] > 0)
            {
                return ['code'=>0,'data'=>'错误：'.$file["error"]];
            } else {
                return ['code'=>1,'data'=>''];
            }
        } else {
            return ['code'=>0,'data'=>$file["type"]];
        }
    }

    /*
       生成唯一自定义文件名称
   */

    public function creatFileName()
    {
        return md5(uniqid(microtime(true),true));
    }


    /*
    接受文件并上传到七牛云
    */

    public function uploadFile( $file )
    {
        // 获取上传凭证token
        $token = $this->getToken();
        // 上传文件的本地路径
        $filePath = $file["tmp_name"];
        // 获取文件后缀名
        $extension = explode(".",$file["name"]);
        // 验证图片格式是否正确
        $validateFormat = $this->validateFormat( $file );
        if ($validateFormat["code"] != 1 ){
            return $validateFormat;
        }
        // 上传到七牛后保存的文件名
        $key = $this->creatFileName().".".end($extension);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret,$err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null ){
            return ['code'=>0,'data'=>'上传失败，请查看详细报错原因'];
        } else {
            if ( count($ret)==2 && $ret["key"]!=""){
                $fileKey = $ret["key"];
                return ['code'=>1,'data'=>$fileKey];
            } else {
                return ['code'=>0,'data'=>'返回数据格式错误'];
            }
        }
    }

    /*
        查找对应文件是否存在
   */

    public function findFile( $key )
    {
        $auth = new Auth( $this->accessKey, $this->secretKey );
        $bucketManager = new BucketManager( $auth );
        $res = $bucketManager->stat( $this->bucKet, $key );
        if ( $res[0] != NULL && $res[1] == NULL ) {
            return ['code'=>1,'data'=>"该文件存在"];
        } else {
            return ['code'=>0,'data'=>"该文件不存在"];
        }
    }

    /*
        删除指定文件
    */

    public function delFile( $key )
    {
        $auth = new Auth( $this->accessKey, $this->secretKey );
        $bucketManager = new BucketManager( $auth );
        $result = $this->findFile( $key );
        if ( $result["code"] ==1 ) {
            $res = $bucketManager->delete( $this->bucKet, $key );
            if ($res == NULL ) {
                return ['code'=>1,'data'=>"删除成功"];
            } else {
                return ['code'=>0,'data'=>"删除失败"];
            }
        } else{
            return ['code'=>0,'data'=>"该图片不存在"];    
        }  
    } 


}